package com.bykj.taketurns.fragment;

import android.app.Activity;
import android.content.Context;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bykj.taketurns.R;
import com.bykj.taketurns.activity.HomeActivity;
import com.bykj.taketurns.application.MyApplication;
import com.bykj.taketurns.homefragment.adapter.ScriptRelaAdapter;
import com.bykj.taketurns.homefragment.bean.HomeBean;
import com.bykj.taketurns.utils.Constant;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.cache.CacheMode;
import com.lzy.okgo.callback.StringCallback;

import okhttp3.Call;
import okhttp3.Response;


public class HomeFragment extends Fragment implements View.OnClickListener, HomeActivity.CompletedAnimListener {

    private HomeActivity activity;
    private View mRootView;
    private TextView detail_tv_script;

    private RecyclerView script_rela;
    private HomeBean homeBean;
    private boolean isFirst ;
    private RelativeLayout script_alldetail_rela;
    private RelativeLayout script_detail_rela;
    private TextView alldetail_tv_script;
    private HomeTextFragment fragment;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            activity.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
        if (mRootView == null) {
            mRootView = inflater.inflate(R.layout.fragment_home, container, false);
            fragment = new HomeTextFragment();

        }
        ViewGroup parent = (ViewGroup) mRootView.getParent();
        if (parent != null) {
            parent.removeView(mRootView);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            View mStateBarFixer = mRootView.findViewById(R.id.status_bar_fix);
            mStateBarFixer.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    getStatusBarHeight(getActivity())));
            mStateBarFixer.setBackgroundColor(getResources().getColor(R.color.home_status));
        }

        return mRootView;
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        initWidget();
        setWidgetState();

    }

    private void initWidget() {
        ImageView pull_down_img = mRootView.findViewById(R.id.pull_down_img);
        ImageView pull_up_img = mRootView.findViewById(R.id.pull_up_img);
        detail_tv_script = mRootView.findViewById(R.id.detail_tv_script);
        alldetail_tv_script = mRootView.findViewById(R.id.alldetail_tv_script);
        script_rela = mRootView.findViewById(R.id.rv_data_home);
        script_alldetail_rela = mRootView.findViewById(R.id.script_alldetail_rela);
        script_detail_rela = mRootView.findViewById(R.id.script_detail_rela);

        mRootView.findViewById(R.id.word_img).setOnClickListener(this);
        pull_down_img.setOnClickListener(this);
        pull_up_img.setOnClickListener(this);

    }

    private void setWidgetState() {
        script_rela.setLayoutManager(new LinearLayoutManager(getActivity()));
        script_rela.setHasFixedSize(true);
    }

    @Override
    public void onResume() {
        super.onResume();
        postData(null);
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.word_img:
                FragmentManager manager = getActivity().getSupportFragmentManager();

                if(!fragment.isAdded()){
                    fragment = (HomeTextFragment) addTextFragment();
                }else {
                    fragment  = (HomeTextFragment) manager.findFragmentByTag("text");
                }
                if (homeBean != null){
                    Bundle bundle = new Bundle();
                    bundle.putString("tid",homeBean.getTopic().getTid());
                    fragment.setArguments(bundle);
                }

                ((HomeActivity) getActivity()).applyRotation(true, fragment, 0, 90, HomeFragment.this);

                //重新绘制
                invalidata();
                break;

            case R.id.pull_down_img:

                script_detail_rela.setVisibility(View.GONE);
                script_alldetail_rela.setVisibility(View.VISIBLE);
                break;

            case R.id.pull_up_img:
                script_detail_rela.setVisibility(View.VISIBLE);
                script_alldetail_rela.setVisibility(View.GONE);
                break;

        }
    }

    @Override
    public void onAttach(Context context) {
        super.onAttach(context);
        activity = (HomeActivity) context;
    }

    //获取状态栏高度
    public static int getStatusBarHeight(Activity a) {
        int result = 0;
        int resourceId = a.getResources().getIdentifier("status_bar_height",
                "dimen", "android");
        if (resourceId > 0) {
            result = a.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MyApplication.getRefWatcher(getActivity()).watch(this);

    }

    @Override
    public void onDetach() {
        super.onDetach();
        activity = null;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        mRootView = null;

    }

    @Override
    public void animEnd(Animation animation) {
        postData(animation);
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        if (hidden) {
            if (!isFirst) {
                //重新绘制
                invalidata();
            }
        } else {
                activity.setCompleteAnimListener(this);
                isFirst = false;
        }
    }

    //进行网络请求数据
    public void postData(final Animation animation) {
        OkGo.get(Constant.JHC_SERVICE + Constant.ServiceConstant.HOME_URL)     // 请求方式和请求url
                .tag(this)
                // 请求的 tag, 主要用于取消对应的请求
                .cacheKey("HomeVideo")
                .cacheMode(CacheMode.IF_NONE_CACHE_REQUEST)
                .execute(new StringCallback() {

                    @Override
                    public void onSuccess(String s, Call call, Response response) {

                        homeBean = activity.gson.fromJson(s, HomeBean.class);

                        detail_tv_script.setText("\t\t" + homeBean.getTopic().getTcontent());

                        alldetail_tv_script.setText("\t\t" + homeBean.getTopic().getTcontent());

                        script_rela.setAdapter(new ScriptRelaAdapter(getActivity(), homeBean.getStoryvideo()));
                        if(animation!=null){}
                           //animation.cancel();
                    }

                    @Override
                    public void onCacheSuccess(String s, Call call) {

                        homeBean = activity.gson.fromJson(s, HomeBean.class);

                        detail_tv_script.setText("\t\t" + homeBean.getTopic().getTcontent());

                        alldetail_tv_script.setText("\t\t" + homeBean.getTopic().getTcontent());

                        script_rela.setAdapter(new ScriptRelaAdapter(getActivity(), homeBean.getStoryvideo()));

                    }
                });
    }

    //重新绘制view
    public void invalidata() {
        homeBean = null;
        if (detail_tv_script==null){
            return;
        }
        detail_tv_script.setText(null);
        script_rela.setAdapter(null);
        mRootView.postInvalidate();
    }


    public Fragment addTextFragment(){
        FragmentTransaction transaction = activity.getSupportFragmentManager().beginTransaction();
        transaction.add(R.id.realtabcontent,fragment,"text");
        transaction.commitAllowingStateLoss();
        return fragment;
    }

}
